package mobidever.godutch.database.base;

import java.util.ArrayList;
import java.util.List;

import mobidever.godutch.database.base.SQLiteHelper.SQLiteDataTable;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public abstract class SQLiteDALBase implements SQLiteDataTable{
	private Context mContext;
	private SQLiteDatabase mDatabase;
	
	protected abstract String[] getTableNameAndPK();
	protected abstract Object FindModel(Cursor pCursor);
	
	public SQLiteDALBase(Context pContext){
		this.mContext = pContext;
	}
	public Context getContext(){
		return mContext;
	}
	public SQLiteDatabase getDatabase(){
		if(mDatabase == null){
			mDatabase = SQLiteHelper.getInstance(mContext).getWritableDatabase();
		}
		Log.i("mylog","getDatabase over");
		return mDatabase;
	}
	public void beginTransaction(){
		mDatabase.beginTransaction();
	}
	public void setTransactionSuccessful(){
		mDatabase.setTransactionSuccessful();
	}
	public void endTransaction(){
		mDatabase.endTransaction();
	}
	public int getCount(String pCondition){
		String _String[] = getTableNameAndPK();
		Cursor _Cursor = ExecSql("Select "+_String[1]+" From "+_String[0]+" Where 1=1 "+pCondition);
		int _Count = _Cursor.getCount();
		_Cursor.close();
		return _Count;
	}
	public int getCount(String pPK,String pTableName,String pCondition){
		Cursor _Cursor = ExecSql("Select "+pPK + " From "+pTableName+" Where 1=1 "+pCondition);
		int _Count = _Cursor.getCount();
		_Cursor.close();
		return _Count;
	}
	protected Boolean Delete(String pTableName,String pCondition){
		return getDatabase().delete(pTableName, "1=1"+pCondition, null) >= 0;
	}
	
	
	protected List getList(String pSqlText){
		Cursor _Cursor = ExecSql(pSqlText);
		return CursorToList(_Cursor);
	}
	public Cursor ExecSql(String pSqlText){
		Cursor _Curosr = getDatabase().rawQuery(pSqlText, null);
		return _Curosr;
	}
	protected List CursorToList(Cursor pCursor){
		List _List = new ArrayList();
		Log.i("mylgo","CursorToList_1 over");
		while(pCursor.moveToNext()){
			Object _Object = FindModel(pCursor);
			_List.add(_Object);
		}
		pCursor.close();
		return _List;
	}
}
